import React from 'react'
import style from './style.employ-management-update'
import styleTransfer from './style.transfer-user'
import { Modal, info, TreeList, error, success, Button, InputList, Input, DateSelect, Select,  Link, TitleBar } from '../../ui-components'
import { FieldBox } from '../../ui-components/form'
import { connect } from 'react-redux'
import util from '../../util'
import { makeTeamTree } from '../team/TeamManage'
import cx from 'classnames'
import {updateProfileTemplateFieldDetailCore} from '../../actions/profileFieldDetail.action'
import { bindActionCreators } from 'redux'
import moment from 'moment';


export default
@connect(({ profileTemplate, team, app, user }) => ({ user,app, team, profileTemplate }), dispatch => ({actions: bindActionCreators({ updateProfileTemplateFieldDetailCore }, dispatch)}))
class TransferUser extends React.Component {

  state = {
    setReporterNull: null,
    notifyUsers: [],
    transferType: '',
    transferDate: '',
    description: '',
    afterReporter: {},
    afterTeamId: '',
    afterJobTitleId: '',
    afterJobLevelId: '',
    jobTitleOpts: [],
    jobLevelOpts: [],
  }

  handleSubmit(submit) {
    const { setReporterNull, notifyUsers, afterReporter, ...others } = this.state
    const { profile, coreProfile, reportLineInfo=[] } = this.props.user
    const reportor = (reportLineInfo.reportors || [])[0] || {}
    const { teamVO={} } = coreProfile
    const { fieldMap } = this.props.profileTemplate
    const fields = fieldMap
    const jobTitle = fields.filter(v => v.referenceName === 'jobTitle')[0]
    const jobLevel = fields.filter(v => v.referenceName === 'jobLevel')[0]
    const { profileFieldVOs=[] } = profile
    const _jobLevel = util.find(profileFieldVOs, v => v.referenceName === 'jobLevel').dataValue || ''
    const _jobTitle = util.find(profileFieldVOs, v => v.referenceName === 'jobTitle').dataValue || ''

    if (util.isNull(others.transferType)) return error('调岗类型不能为空!')
    if (util.isNull(others.transferDate)) return error('调岗日期不能为空!')
    if (util.isNull(others.afterTeamId)) return error('调岗后部门不能为空!')
    if (util.isNull(afterReporter) && !submit) {
      this.setState({
        setReporterNull: true
      })
      return
    }
    //if (util.isNull(others.afterJobTitleId)) return error('调岗后职位不能为空!')
    //if (util.isNull(others.afterJobLevelId)) return error('调岗后职级不能为空!')

    info('提交中...', true)
    this.props.transferUser(
      {
        ...others,
        userId: this.props.params.userId,
        toNotifyUserIds: notifyUsers.map(user => user.userId),
        afterReporterId: util.isNull(afterReporter)? null: afterReporter.userId,
        beforeTeamId: teamVO.teamId,
        beforeReporterId: reportor.userId,
        beforeJobTitleId: _jobTitle,
        beforeJobLevelId: _jobLevel,
      },
      () => {
        success('提交成功!')
        this.props.router.push('/hr/reorg/transfer')
      }
    )
  }

  renderJobTitle(jobTitle, { dataValue }) {
    if (!jobTitle) return null
    return (
      <Select label={'调岗后职位'} width={260} value={this.state.afterJobTitleId || dataValue  } onChange={(e) => this.updateField(e.target.value, 'afterJobTitleId')}>
        <option value="">选择职位..</option>
        {
          this.state.jobTitleOpts.map((v, i) => (
            <option key={i} value={v.orgPickOptionId}>{ v.optionValue }</option>
          ))
        }
      </Select>
    )
  }

  renderJobLevel(jobLevel, { dataValue }) {
    if (!jobLevel) return null
    return (
      <Select label="调岗后职级" width={260} value={this.state.afterJobLevelId || dataValue } onChange={e => this.updateField(e.target.value, 'afterJobLevelId')}>
        <option value="">选择职级...</option>
        {
          this.state.jobLevelOpts.map((v, i) => (
            <option key={i} value={v.orgPickOptionId}>{ v.optionValue }</option>
          ))
        }
      </Select>
    )
  }

  renderTeams(prev) {
    let { teams } = this.props.team
    const rootTeam = makeTeamTree(teams)[0]
    return (
      <TreeList
        className={style['tree-list']} width={260}
        onClick={team => this.updateField(team.teamId, 'afterTeamId')}
        root={rootTeam}
        label="调岗后部门"
        value={prev}
      />
    )
  }

  componentWillReceiveProps(props) {
    if (props.params.userId != this.props.params.userId) {
      this.fetchUserCoreProfile(props)
      this.fetchUserProfile(props)
    }

    if (util.isNull(this.props.user.coreProfile) && !util.isNull(props.user.coreProfile)) {
      this.props.fetchProfileTemplateFields(props.user.coreProfile.profileTemplateId)
      this.setState({
        afterTeamId: props.user.coreProfile.teamVO.teamId
      })
    }

    if (util.isNull(this.props.user.profile) && !util.isNull(props.user.profile)) {
      const { profileFieldVOs } = props.user.profile
      const jobLevel = util.find(profileFieldVOs, v => v.referenceName == 'jobLevel')
      const jobTitle = util.find(profileFieldVOs, v => v.referenceName == 'jobTitle')
      this.setState({
        afterJobLevelId: jobLevel.dataValue,
        afterJobTitleId: jobTitle.dataValue
      });
    }
    if (util.isNull(this.props.user.reportLineInfo) && !util.isNull(props.user.reportLineInfo)) {
      const reportor = (props.user.reportLineInfo.reportors || [])[0] || {}
      this.setState({
        afterReporter: reportor
      })
    }
  }

  componentWillUnmount() {
    this.props.resetUser()
    this.props.resetTeam()
  }

  fetchUserCoreProfile(props) {
    props = props || this.props
    this.props.fetchUserCoreProfile(props.params.userId)
  }

  fetchUserProfile(props) {
    props  = props || this.props

    this.props.fetchUserProfile(props.params.userId)
  }

  fetchReportLineInfo(props) {
    props = props || this.props
    this.props.fetchReportLineInfo(props.params.userId)
  }
  
  componentDidMount() {
    this.fetchUserCoreProfile()
    this.fetchReportLineInfo()
    this.fetchUserProfile()
    this.props.fetchTeamData()
    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 1
    }, (opts) => {
      this.setState({
        jobTitleOpts: opts,
      });
    });

    this.props.actions.updateProfileTemplateFieldDetailCore({
      configType: 2
    }, (opts) => {
      this.setState({
        jobLevelOpts: opts,
      });
    });
  }

  updateField(value, name) {
    this.setState({
      ...this.state,
      [name]: value
    })
  }

  render() {
    const { profile, coreProfile, reportLineInfo=[] } = this.props.user
    const reportor = (reportLineInfo.reportors || [])[0] || {}
    const { teamVO={} } = coreProfile
    const { fieldMap } = this.props.profileTemplate
    const fields = fieldMap
    const jobTitle = fields.filter(v => v.referenceName === 'jobTitle')[0]
    const jobLevel = fields.filter(v => v.referenceName === 'jobLevel')[0]
    const { profileFieldVOs=[] } = profile
    const _jobLevel_obj = util.find(profileFieldVOs, v => v.referenceName === 'jobLevel')
    const _jobTitle_obj = util.find(profileFieldVOs, v => v.referenceName === 'jobTitle')
    const prevJobLevelName = util.find(this.state.jobLevelOpts, v => v.orgPickOptionId === _jobLevel_obj.dataValue).optionValue
    const prevJobTitleName = util.find(this.state.jobTitleOpts, v => v.orgPickOptionId === _jobTitle_obj.dataValue).optionValue
    
    return (
      <div className={style.root}>
        <TitleBar
          back
          label="办理调岗"
        />
        <div className={cx(style.list, styleTransfer.list)}>
          <div className={style.user}> 
            <FieldBox label={'调岗对象'}>
              <div className={style['avatar']}>
                <Link 
                  noHover
                  src={coreProfile.avatarUrl}
                  srcIcon="avatar"
                  width="120"
                />
                <span style={{ marginLeft: '0px', color: '#fff' }}>{ coreProfile.fullName || '' }</span>
              </div>
            </FieldBox>
          </div>
          <div>
            <div>
              <Input tip={'如：平级调动、降级等（必填）'} label={'调岗类型'} width={260} value={this.state.transferType} onChange={e => this.updateField(e.target.value, 'transferType')}/>
            </div>
          </div>
          <div>
            <div>
              <DateSelect
                time={this.state.transferDate && moment(+this.state.transferDate).format('YYYY-MM-DD')}
                label={'正式调岗日期'} width={260}
                onChange={v => this.updateField(v, 'transferDate')}
              />
            </div>
          </div>
          <div>
            <i>当前部门: { teamVO.teamName || '' }</i>
            <div>
              { this.renderTeams(teamVO) }
            </div>
          </div>
          <div>
            <i>当前汇报对象: { reportor.fullName || '' }</i>
            <div>
              <InputList 
                onSelect={user => this.setState({
                  afterReporter: user
                })}
                value={reportor.fullName || ''}
                width={260}
                label={'调岗后汇报对象'}
                fetch={this.props.fetchAtList}
                clear={this.props.clearAtList}
                list={this.props.app.atList}
              />
            </div>
          </div>
          <div>
            <i>当前职位: { prevJobTitleName || '' }</i>
            <div>
              { this.renderJobTitle(jobTitle, _jobTitle_obj) }
            </div>
          </div>
          <div>
            <i>当前职级: { prevJobLevelName || '' }</i>
            <div>
              { this.renderJobLevel(jobLevel, _jobLevel_obj) }
            </div>
          </div>
          <div>
            <div>
              <Input label={'说明'} width={260} multi value={this.state.description} onChange={e => this.updateField(e.target.value, 'description')}/>
            </div>
          </div>
          <div>
            <div>
              <div>
                <InputList 
                  keep={false}
                  label={'通知以下人员'}
                  onSelect={user => this.setState({
                    notifyUsers: [
                      ...this.state.notifyUsers,
                      user
                    ]
                  })}
                  width={260}
                  excludeList={this.state.notifyUsers}
                  fetch={this.props.fetchAtList}
                  clear={this.props.clearAtList}
                  list={this.props.app.atList}
                />
                {
                  this.state.notifyUsers? (
                    <ul style={{ paddingLeft: '143px' }} className={style['notify-users']}>
                      {
                        this.state.notifyUsers.map((v, i) => (
                          <li key={i}>
                            <span>{ v.fullName }</span>
                            <Link icon="close" onClick={() => this.setState({
                              notifyUsers: this.state.notifyUsers.filter(user => user.userId != v.userId)
                            })}/>
                          </li>
                        ))
                      }
                    </ul>
                  ): null
                }
              </div>
            </div>
          </div>
          <Button style={{ marginLeft: '143px' }} label="提交" onClick={() => this.handleSubmit()}/>
        </div>
        <Modal
          active={this.state.setReporterNull}
          onRequestClose={() => this.setState({ setReporterNull: false })}
          actions={['cancel', () => { this.setState({ setReporterNull: false });this.handleSubmit(true); }]}
          title="确认提交"
        >
          <div>点击确定，该成员将被设置为“没有汇报对象”，是否继续？</div>
        </Modal>
      </div>
    )
  }
}
